<template>
    <div>
        <el-card shadow="always" :body-style="{ padding: '40px' }">
            <el-button type="primary" size="small" @click="addTrade" icon="el-icon-plus" v-visite="'btn.Trademark.add'" v-if="$hideBtn('btn.Trademark.add')">添加</el-button>
            <el-table :data="tradeList" border stripe style="margin:20px 0">
                <el-table-column label="序号" type="index" align="center" width="80">
                </el-table-column>
                <el-table-column label="品牌名称" prop="tmName">
                </el-table-column>
                <el-table-column label="品牌LOGO">
                    <template v-slot="{row,$index}">
                        <img :src="row.logoUrl" alt="" style="width:80px;height:50px">
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{row,$index}">
                        <el-button type="warning" size="small"   v-if="$hideBtn('btn.Trademark.update')" @click="editTrade(row)" icon="el-icon-edit"></el-button>
                        
                        <el-popconfirm title="这是一段内容确定删除吗？" @confirm="deleteBtn(row)">
                            <el-button slot="reference" v-visite="`btn.Trademark.remove`" v-if="$hideBtn('btn.Trademark.remove')" style="margin:0 20px" type="danger" size="small"
                            icon="el-icon-delete"></el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page.sync="currentPage"
                :page-sizes="[2,3,5,7]" :page-size="pageSize" layout="prev, pager, next, jumper,->,sizes,total"
                :total="total" background :pager-count="7">
            </el-pagination>
            <!-- 添加时弹出的对话框 -->
            <el-dialog title="添加品牌" :visible.sync="dialogFormVisible" v-el-drag-dialog >
                <el-form style="width:80%" :model="trade" :rules="rules" ref="formRef">
                    <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                        <el-input autocomplete="off" v-model="trade.tmName"></el-input>
                        
                    </el-form-item>
                    <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
                        <el-upload class="avatar-uploader" action="/dev-api/admin/product/upload"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="trade.logoUrl" :src="trade.logoUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="save">确 定</el-button>
                </div>
            </el-dialog>

        </el-card>

    </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
import { trademark as trade } from "@/api"
import { nextTick } from "process";
export default {
    components: {},
    data: () => {
        const nameValidate = (rule, value, next) => {
            if (value.trim().length > 1 && value.trim().length < 11) {
                next()
            }
            next(new Error("品牌名称长度必须是2~10字符！"))
        };
        const imgValidate = (rule, value, next) => {
            if (value) {
                next()
            }
            next(new Error("请上传图片"))
        }


        return {
            pageSize: 3,
            currentPage: 1,
            dialogFormVisible: false,

            trade: {
                tmName: "",
                logoUrl: ""
            },
            rules: {
                tmName: [
                    { validator: nameValidate, trigger: 'change' },
                    { required: true, message: '请输入品牌名称', trigger: 'blur' },
                ],
                logoUrl: [
                    { validator: imgValidate, trigger: 'change' }
                ]
            },

        }
    },
    methods: {
        ...mapActions(["getTradeList", "addOrEditTrade", "deleteTrade"]),
        sizeChange(pageSize) {
            this.pageSize = pageSize;
            this.currentPage = 1;
            this.getTradeList({ page: this.currentPage, limit: this.pageSize });
        },
        currentChange(currentPage) {
            // console.log(this.currentPage,currentPage);  sync已经实现了同步
            this.getTradeList({ page: this.currentPage, limit: this.pageSize });
        },
        addTrade() {
            this.dialogFormVisible = true;

            nextTick(() => {
                this.$refs.formRef.resetFields();
                this.trade.tmName = "";
                this.trade.logoUrl = "";
                this.trade.id = "";
            })
        },
        //上传的一些回调
        handleAvatarSuccess(res, file) {
            this.trade.logoUrl = res.data;
        },
        //   上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
        beforeAvatarUpload(file) {
            const type = file.type;
            const size = file.size;
            if (type === "image/jpeg" || type === "image/png" || type === "image/gif") {
                if (size / 1024 / 1024 > 5) {
                    this.$message.error("上传头像图片大小不能超过 5MB!");
                    return false;
                }
                return true;

            } else {
                this.$message.error('上传头像图片必须是jpeg / png / gif 格式!');
                return false;
            }
        },
        //   保存时表单验证
        save() {

            this.$refs.formRef.validate(async (isTrue) => {
                if (isTrue) {
                    try {
                        await this.addOrEditTrade(this.trade);
                        this.dialogFormVisible = false;
                        this.getTradeList({ page: this.currentPage, limit: this.pageSize });
                        this.$message.success(this.trade.id ? "修改成功" : "添加成功");
                    } catch (error) {
                        this.$message.error(this.trade.id ? "修改失败" : "添加失败");

                    }
                }
            })
        },
        //修改品牌的回调
        editTrade(row) {
            this.dialogFormVisible = true;
            nextTick(() => {
                this.$refs.formRef.resetFields();
                this.trade.tmName = row.tmName;
                this.trade.logoUrl = row.logoUrl;
                this.trade.id = row.id;
            })

        },


        // 删除品牌的回调
        async deleteBtn(row) {
            try {
                console.log("row", row);
                await this.deleteTrade(row.id);
                this.getTradeList({ page: this.currentPage, limit: this.pageSize });               
                this.$message.success("删除djdsfhs成功");

            } catch (error) {
                
                this.$message.error("删除失败")
            }
        }

    },
    computed: {
        ...mapState({ tradeList: state => state.trademark.tradeList, total: state => state.trademark.total })
    },
    mounted() {
        this.getTradeList({ page: this.currentPage, limit: this.pageSize });
    },
    


}
</script>

<style  scoped>

</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>